#include "cserverclientcarposition.h"
#include "globalStructs.h"
#include <QNetworkRequest>
#include <QUrl>
#include <QMessageBox>
CServerClientCarPosition::CServerClientCarPosition()
{
    m_commandID = SERVER_CLIENT_CAR_POSITION;
    m_ArgCount = 4; // for we have 4 factors not including the "command ID"
    m_networkAccessManager = new QNetworkAccessManager(this);
}

CServerClientCarPosition::~CServerClientCarPosition()
{
    delete m_networkAccessManager;

    if (m_pListReply != NULL)
        delete m_pListReply;
}

QList<QString>& CServerClientCarPosition::formInteresedItemList()
{
    m_interestedList.append(QString("Person ID"));
    m_interestedList.append(QString("Taxi ID"));
    m_interestedList.append(QString("Latitude"));
    m_interestedList.append(QString("Longitude"));
    m_interestedList.append(QString("Command ID"));


    return m_interestedList;
}

QMultiMap<QString, QString>* CServerClientCarPosition::formResult()
{
    m_xmlString = QString::fromUtf8(m_pListReply->readAll());
    if ( m_xmlString.isEmpty() )
    {
        // no contents have been read or an error occures
        return NULL;
    }

    if(this->isReplyStringRight() == false)
    {
        return NULL;
    }

    this->formInteresedItemList();

    QDomElement root = m_pXMLDocument->documentElement();

    QDomElement element = root.firstChildElement("positions");

    if (!element.isNull())
    {
        QDomElement child = element.firstChildElement("position");

        while (!child.isNull())
        {
            m_personID = child.attribute("personId");
            m_result.insert(m_interestedList[7], m_personID);

            m_taxiID =  child.attribute("carId");
            m_result.insert(m_interestedList[0], m_taxiID);

            m_Lat = child.attribute("lat");
            m_result.insert(m_interestedList[5], m_Lat);

            m_Lon = child.attribute("lon");
            m_result.insert(m_interestedList[6], m_Lon);

            //lastly insert the command ID
            m_result.insert("Command ID", QString::number(m_commandID) );

            child = child.nextSiblingElement("position");
        }
    }

    return &m_result;
}
